import { hexMD5 } from "../../utils/md5.js"
    
const app = getApp()

Page({
  data: {
    account: '',
    password: ''
  },

  onLoad: function (options) {

	},

  login: function () {
    let _this = this
    //调用wx.login接口，获取code，即下面的res.code
    wx.login({
      success: (res) => {
        wx.request({
          url: 'http://testapi.yunyuekj.com/alarm/api/WXOpen/OnLogin', //调用后端接口,获取openid
          header: {
            'content-type': 'application/json;charset=UTF-8'
          },
          method: 'POST',
          data: {
            Code: res.code  //以post方式向后端发送code
          },
        //从后端接口得到的响应，即res.data
          success: (res) => {
            // setTimeout(() => {
            //   wx.switchTab({
            //     url: '/pages/alarm/index',
            //   })
            // }, 320);
            // return
            if(!_this.data.account) {
              wx.showToast({
                title: '请输入账号',
                icon: 'none',
              })
              return
            }
            if(!_this.data.password) {
              wx.showToast({
                title: '请输入密码',
                icon: 'none',
              })
              return
            }
            var params = {
              LoginName: this.data.account,
              Password: hexMD5(this.data.password),
              WxOpenId: res.data.Data.OpenId,
              OperatorType: 2,
              VerifyCode: '',
            }
            wx.request({
              url: 'http://testapi.yunyuekj.com/alarm/api/Account/Login',
              header: {
                'content-type': 'application/json;charset=UTF-8'
              },
              method: 'POST',
              data: params,    
    
              success: function (res) {
                app.setToken('token',res.data.Data.Token)
                //缓存全局保存
                app.globalData.token = res.data.Data.Token;
                setTimeout(() => {
                  wx.switchTab({
                    url: '/pages/alarm/index',
                  })
                }, 320);
              }
            })
            return
            wx.setStorage({  // 将token保存在storage本地缓存中
              key: 'token',
              data: res.data.data
            })
          },
          fail: (error) => {
            // 输出错误信息到控制台或日志
            console.error("QwQ请求失败:", error);          
            // 弹出提示框显示错误信息
            wx.showToast({
              title: '请求失败',
              icon: 'none',
              duration: 2000
            });
          }
        })
      }
    })
  }
});